package ai.peanut.selfbms.controller.sys;

import ai.peanut.selfbase.common.domain.DataResult;
import ai.peanut.selfbase.common.enums.ResultTypeEnum;
import ai.peanut.selfbase.modules.user.pojo.UserParam;
import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import com.google.code.kaptcha.Constants;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ThreadContext;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

@Slf4j
@Controller
public class LoginController {

    @Autowired
    private DefaultWebSessionManager defaultWebSessionManager ;


    @RequestMapping("/getCaptcha")
    public void captcha(HttpServletResponse response)throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        Properties properties = new Properties();
        properties.put("kaptcha.border", "no");
        properties.put("kaptcha.textproducer.font.color", "black");
        properties.put("kaptcha.textproducer.char.space", "5");
        Config config = new Config(properties);
        DefaultKaptcha producer = new DefaultKaptcha();
        producer.setConfig(config);
        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到shiro session
        SecurityUtils.getSubject().getSession().setAttribute(
                Constants.KAPTCHA_SESSION_KEY, text);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
    }



    @RequestMapping(value = "/toLogin", method = RequestMethod.POST)
    @ResponseBody
    public DataResult loginl(@RequestBody UserParam userParam , HttpServletRequest request, HttpServletResponse response){
        try{
            Session session = SecurityUtils.getSubject().getSession() ;
            Object beforeCapt = session.getAttribute(
                    Constants.KAPTCHA_SESSION_KEY);
            if(beforeCapt == null ){
                return DataResult.faild(ResultTypeEnum.CODE_TIMEOUT.getCode(),
                        ResultTypeEnum.CODE_TIMEOUT.getMessage());
            }
            session.removeAttribute(Constants.KAPTCHA_SESSION_KEY);
            if( !userParam.getCaptcha().equals((String)beforeCapt) ) {
                return DataResult.faild(ResultTypeEnum.CODE_ERROR.getCode(),
                        ResultTypeEnum.CODE_ERROR.getMessage());
            }

            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(userParam.getLoginName(), userParam.getPassword());
            subject.login(token);
        }catch (UnknownAccountException e) {
            return DataResult.faild(ResultTypeEnum.UNKNOWNACCOUNT.getCode(),
                    ResultTypeEnum.UNKNOWNACCOUNT.getMessage());
        }catch (IncorrectCredentialsException e) {
            return DataResult.faild(ResultTypeEnum.INCORRECTCREDENTIALS.getCode(),
                    ResultTypeEnum.INCORRECTCREDENTIALS.getMessage());

        }catch (LockedAccountException e) {
            return DataResult.faild(ResultTypeEnum.LOCKEDACCOUNT.getCode(),
                    ResultTypeEnum.LOCKEDACCOUNT.getMessage());
        }catch (DisabledAccountException e) {
            return DataResult.faild(ResultTypeEnum.DISABLEDACCOUNT.getCode(),
                    ResultTypeEnum.DISABLEDACCOUNT.getMessage());
        }catch (AuthenticationException e) {
            return DataResult.faild(ResultTypeEnum.AUTHENTICATIONEXCEPTION.getCode(),
                    ResultTypeEnum.AUTHENTICATIONEXCEPTION.getMessage());
        }catch (Exception e) {
            return DataResult.faild(ResultTypeEnum.FAILED.getCode(),
                    ResultTypeEnum.FAILED.getMessage());
        }
        return DataResult.success();
    }


    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    @ResponseBody
    public DataResult logout( HttpServletRequest request, HttpServletResponse response){

        try {
            Subject subject = SecurityUtils.getSubject() ;
            subject.logout();

        } catch (Exception e) {
            log.info("用户推出异常", e ) ;
            return DataResult.faild(ResultTypeEnum.FAILED.getCode(),
                    ResultTypeEnum.FAILED.getMessage());
        }
        return DataResult.success() ;
    }


    @RequiresPermissions("user1:update")
    @RequestMapping(value = "/user1/update", method = RequestMethod.GET)
    @ResponseBody
    public int user1Upadte( HttpServletRequest request, HttpServletResponse response){

        return 0;
    }

}
